﻿

namespace Vampirewal.Core.WPF.Theme;

/// <summary>
/// CustomSelectorView.xaml 的交互逻辑
/// </summary>
[VampirewalIoCRegister("CustomSelectorView")]
public sealed partial class CustomSelectorView : AddOrEditUcViewBase
{
    public CustomSelectorView()
    {
        InitializeComponent();
    }

    public override string ViewModelKey => "CustomSelectorViewModel";

    private void DataGrid_Loaded(object sender, RoutedEventArgs e)
    {
        var csVM = this.DataSource as CustomSelectorViewModel;

        dg.Columns.Clear();

        #region 新增checkBox

        DataGridTemplateColumn check = new DataGridTemplateColumn();
        check.Header = "选择";
        check.Width = 50;

        DataTemplate dt = new DataTemplate();
        FrameworkElementFactory checkFactory = new FrameworkElementFactory(typeof(CheckBox));
        Binding check_binding = new Binding("IsChecked");
        check_binding.Mode = BindingMode.TwoWay;
        check_binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

        checkFactory.SetBinding(CheckBox.IsCheckedProperty, check_binding);

        dt.VisualTree = checkFactory;
        check.CellTemplate = dt;

        dg.Columns.Add(check);

        #endregion

        var entityAttr= csVM.EntityType.GetCustomAttribute<CustomSelectorEntityAttribute>();


        foreach (var item in csVM.EntityType.GetProperties())
        {
            if (entityAttr.CustomSelectorIgnorePropertyName.Contains(item.Name)) continue;

            var attr = item.GetCustomAttribute<CustomSelectorPropertyAttribute>();
            if (attr == null) continue;

            DataGridTextColumn tc = new DataGridTextColumn();
            tc.Header = attr.Header;
            tc.IsReadOnly = true;

            if (attr.Width > 50)
            {
                tc.SetValue(DataGridTextColumn.WidthProperty, new DataGridLength(attr.Width));
            }


            Binding binding = new Binding($"Value.{item.Name}");
            if (!string.IsNullOrEmpty(attr.ConverterName))
            {
                var converterType= Type.GetType(attr.ConverterName);
                var converter = Activator.CreateInstance(converterType) as IValueConverter;

                binding.Converter = converter;
            }

            tc.Binding = binding;

            dg.Columns.Add(tc);
        }

        if (!string.IsNullOrEmpty(entityAttr.SelectButtonStyleKey))
        {
            var btnStyle= Application.Current.Resources[entityAttr.SelectButtonStyleKey] as Style;
            if(btnStyle != null)
            {
                selectBtn.Style = btnStyle;
            }
        }
    }
}

[VampirewalIoCRegister("CustomSelectorViewModel")]
internal partial class CustomSelectorViewModel : ViewModelBase
{
    public CustomSelectorViewModel()
    {
        Data = new ObservableCollection<CustomData<object>>();
    }

    [ObservableProperty]
    private Type entityType;

    public override void PassData(object obj)
    {
        if (obj == null) CloseView();

        if (obj is IList list && list.Count > 0 )
        {
            // 安全转换逻辑

            EntityType = list[0].GetType();

            var attr = EntityType.GetCustomAttribute<CustomSelectorEntityAttribute>();

            if (attr == null) throw new ArgumentNullException($"实体类上缺失{nameof(CustomSelectorEntityAttribute)}特性!");

            Title = $"选择 {attr.Title} 数据";

            Data.Clear();

            foreach (var item in list)
            {
                //var eb = item as TopModel;

                CustomData<object> custom = new CustomData<object>(item);

                Data.Add(custom);
            }
        }
    }

    private bool IsOK { get; set; }

    public override object GetResult()
    {
        if (!IsOK)
        {
            return null;
        }

        var values = Data.Where(w => w.IsChecked).ToList().Select(s => s.Value).ToList();

        return values;
    }

    protected override void CloseView()
    {
        WindowsManager.Instance.CloseDialogWindow(ViewId);
    }

    /// <summary>
    /// 数据源
    /// </summary>
    [ObservableProperty]
    private ObservableCollection<CustomData<object>> data;

    [RelayCommand]
    private void Select()
    {
        IsOK = true;
        CloseView();
    }
}

internal partial class CustomData<T> : TopModel where T : class
{
    public CustomData(T t)
    {
        Value = t;
    }

    [ObservableProperty]
    private T value;
}